//
//  GQProfileInviteFriendController.m
//  GuQu
//
//  Created by HELIUM STAR on 15/5/28.
//  Copyright (c) 2015年 HELIUM STAR. All rights reserved.
//

#import "GQProfileInviteFriendController.h"
#import "GQHomeFamousCell.h"
#import "GQProfileSearbarController.h"
#import "GQProfileNearController.h"
#import "GQProfileContactContrller.h"
#import "GQProfileContact.h"
#import <AddressBook/AddressBook.h>

@interface GQProfileInviteFriendController () <UITableViewDataSource, UITableViewDelegate>

@property (strong, nonatomic) NSArray *imageArr;
@property (strong, nonatomic) NSArray *nameArr;
@property (strong, nonatomic) NSArray *colorArr;
@property (assign, nonatomic) NSInteger count;

@end

@implementation GQProfileInviteFriendController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"查找邀请好友";
    self.view.backgroundColor = [UIColor colorWithRed:236/255.0 green:236/255.0 blue:236/255.0 alpha:1.0];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageWithOriginalName:@"distribute_back"] style:UIBarButtonItemStylePlain target:self action:@selector(backToPre)];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageWithOriginalName:@"home_search"] style:UIBarButtonItemStyleDone target:self action:@selector(searchItemClick)];
    [self setUpChildView];
}

- (void)backToPre
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)searchItemClick
{
    GQProfileSearbarController *GQPSC = [[GQProfileSearbarController alloc] init];
    [self.navigationController pushViewController:GQPSC animated:YES];
}

- (void)setUpChildView
{
    
    UIView *containView = [[UIView alloc] init];
    containView.x = 0;
    containView.y = kNavigatationBarHeight;
    containView.width = self.view.width;
    containView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:containView];
    
    //创建图标
    CGFloat margin = 15;
    CGFloat width = (self.view.width - margin * 6) / 5;
    NSInteger count = 5;
    for (int i = 0; i < 5; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.x = margin + i % count * (margin + width);
        btn.y = 10;
        btn.width = width;
        btn.tag = i;
        
        [btn addTarget:self action:@selector(btnDidClick:) forControlEvents:UIControlEventTouchUpInside];
        
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:self.imageArr[i]]];
        imageView.x = 0;
        imageView.y = 0;
        imageView.width = btn.width;
        imageView.height = btn.width;
        [btn addSubview:imageView];
        
        UILabel *titleLabel = [[UILabel alloc] init];
        titleLabel.x = 0;
        titleLabel.y = CGRectGetMaxY(imageView.frame);
        titleLabel.width = btn.width;
        titleLabel.height = 20;
        titleLabel.text = self.nameArr[i];
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.textColor = [UIColor blackColor];
        titleLabel.font = [UIFont systemFontOfSize:12];
        [btn addSubview:titleLabel];
        btn.height = CGRectGetMaxY(titleLabel.frame);
        [containView addSubview:btn];
    }
    containView.height = width + 40;
    
    //古趣推荐
    UILabel *label = [[UILabel alloc] init];
    label.x = 10;
    label.y = CGRectGetMaxY(containView.frame) + 10;
    label.width = 100;
    label.height = 12;
    label.text = @"古趣推荐";
    label.textColor = [UIColor blackColor];
    label.font = [UIFont systemFontOfSize:12];
    [self.view addSubview:label];
    
    UITableView *tableView = [[UITableView alloc] init];
    tableView.x = 0;
    tableView.y = CGRectGetMaxY(label.frame) + 5;
    tableView.width = self.view.width;
    tableView.height = self.view.height - tableView.y;
    tableView.delegate = self;
    tableView.dataSource = self;
    [tableView registerClass:[GQHomeFamousCell class] forCellReuseIdentifier:kFlag];
    [self.view addSubview:tableView];
    
}

- (void)btnDidClick:(UIButton *)btn
{
    if (btn.tag == 4) {
        GQProfileNearController *GQPNC = [[GQProfileNearController alloc] init];
        [self.navigationController pushViewController:GQPNC animated:YES];
    }
    if (btn.tag == 3) {
        [self getAddressBook];
        
//        ABAuthorizationStatus status = ABAddressBookGetAuthorizationStatus();
//        if (status != kABAuthorizationStatusAuthorized) {
//            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"请在设置中授权给本程序" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
//            [alertView show];
//        }
        
    }
}

- (void)getAddressBook
{
    ABAuthorizationStatus status = ABAddressBookGetAuthorizationStatus();
    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
    NSLog(@"%ld", status);
    if (status == kABAuthorizationStatusNotDetermined) {
        
        ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
            if (granted) {
//                GQProfileContactContrller *GQPCC = [[GQProfileContactContrller alloc] init];
//                [self.navigationController pushViewController:GQPCC animated:YES];
                NSLog(@"用户授权成功");
            } else {
                NSLog(@"用户授权失败");
            }
        });
    }
    
    if (status == kABAuthorizationStatusAuthorized) {
        
        NSMutableArray *phoneArrM = [NSMutableArray array];
        CFArrayRef peopelArray = ABAddressBookCopyArrayOfAllPeople(addressBook);
        CFIndex peopleCount = CFArrayGetCount(peopelArray);
        for (CFIndex i = 0; i < peopleCount; i++) {
            //获取具体的联系人
            GQProfileContact *GQPC = [[GQProfileContact alloc] init];
            ABRecordRef person = CFArrayGetValueAtIndex(peopelArray, i);
            
            //获取具体的联系人
            NSString *firstName = (__bridge_transfer NSString *) ABRecordCopyValue(person, kABPersonFirstNameProperty);
            NSString *lastName = (__bridge_transfer NSString *) ABRecordCopyValue(person, kABPersonLastNameProperty);
           // NSLog(@"%@ --- %@", firstName, lastName);
            
            NSString *name = nil;
            if (!firstName && !lastName) {
                name = @"未命名";
            }else if (!firstName) {
                name = lastName;
            }else if(!lastName){
                name = firstName;
            }else{
                name = [NSString stringWithFormat:@"%@%@", lastName, firstName];
            }
           // NSLog(@"%@", name);
            GQPC.name = name;
            
            
            //获取联系人的姓名
            ABMultiValueRef phones = ABRecordCopyValue(person, kABPersonPhoneProperty);
            CFIndex phoneCount = ABMultiValueGetCount(phones);
            NSMutableArray *arrM = [NSMutableArray array];
            for (CFIndex i = 0; i < phoneCount; i++) {
//                NSString *phoneLabel = (__bridge_transfer NSString *)ABMultiValueCopyLabelAtIndex(phones, i);
                NSString *phoneValue = (__bridge_transfer NSString *)ABMultiValueCopyValueAtIndex(phones, i);
                phoneValue = [phoneValue stringByReplacingOccurrencesOfString:@"-" withString:@""];
                phoneValue = [phoneValue stringByReplacingOccurrencesOfString:@"(" withString:@""];
                phoneValue = [phoneValue stringByReplacingOccurrencesOfString:@")" withString:@""];
                phoneValue = [phoneValue stringByReplacingOccurrencesOfString:@"." withString:@""];
                phoneValue = [phoneValue stringByReplacingOccurrencesOfString:@"." withString:@""];
                [arrM addObject:phoneValue];
            }
            GQPC.phoneNums = arrM;
            
            CFRelease(phones);
            
            if (ABPersonHasImageData(person)) {
                NSData *imageData = (__bridge_transfer NSData *)ABPersonCopyImageDataWithFormat(person, kABPersonImageFormatThumbnail);
                UIImage *image = [UIImage imageWithData:imageData];
               // NSLog(@"%@", image);
                GQPC.image = image;

            }else{
                UIImage *image = [UIImage imageNamed:self.colorArr[_count % 3]];
                GQPC.image = image;
                _count++;
            }
            [phoneArrM addObject:GQPC];
        }
        
        
        CFRelease(addressBook);
        CFRelease(peopelArray);
        
        GQProfileContactContrller *GQPCC = [[GQProfileContactContrller alloc] init];
        GQPCC.phoneArr = phoneArrM;
       // NSLog(@"%@", GQPCC.phoneArr);
        [self.navigationController pushViewController:GQPCC animated:YES];
    }
    
    if (status == kABAuthorizationStatusDenied) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"请在设置中授权给本程序" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alertView show];
    }
    
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 10;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    GQHomeFamousCell *cell = [tableView dequeueReusableCellWithIdentifier:kFlag forIndexPath:indexPath];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

- (NSArray *)imageArr
{
    if (_imageArr == nil) {
        _imageArr = [NSMutableArray arrayWithObjects:@"share_wechat", @"profile_friendQQ", @"profile_friendMicro", @"profile_contact", @"profile_nearFriend", nil];
    }
    return _imageArr;
}

- (NSArray *)nameArr
{
    if (_nameArr == nil) {
        _nameArr = [NSMutableArray arrayWithObjects:@"微信", @"QQ", @"微博", @"通讯录", @"附近", nil];
    }
    return _nameArr;
}

- (NSArray *)colorArr
{
    if (_colorArr == nil) {
        _colorArr = [NSArray arrayWithObjects:@"profile_icon1", @"profile_icon2", @"profile_icon3", nil];
    }
    return _colorArr;
}

@end
